package cn.tedu.toa.management.sys.controller;

import cn.tedu.toa.management.commons.vo.Result;
import cn.tedu.toa.management.ex.ServiceException;
import cn.tedu.toa.management.sys.service.ex.*;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class SysExceptionHandle {

    @ExceptionHandler(ServiceException.class)
    public Result hanleException(Throwable e){
        //根据异常的类型将对应的状态码值和异常信息分装到 Result对象并返回
        if(e instanceof RecordNotFoundException){
            return Result.failure(Result.State.RECORD_NOT_FOUND_ERR,e);
        }else if(e instanceof ParamIllegelException){
            return Result.failure(Result.State.PARAM_ILLEFAL_ERR,e);
        }else if(e instanceof IllegalOperationException){
            return Result.failure(Result.State.ILLEGAL_OPERATION_ERR,e);
        }else if(e instanceof DeleteException){
            return Result.failure(Result.State.DELETE_ERR,e);
        } else if(e instanceof ParentNodeNotFoundException){
            return Result.failure(Result.State.PARENT_NODE_NOT_FOUND_ERR,e);
        }else if(e instanceof InsertException){
            return Result.failure(Result.State.INSERT_ERR,e);
        }else if(e instanceof UpdateException){
            return Result.failure(Result.State.UPDATE_ERR,e);
        }else if(e instanceof UserNameIsUsedException){
            return Result.failure(Result.State.USERNAME_IS_USED_ERR,e);
        }else if(e instanceof RoleNotChoosedException){
            return Result.failure(Result.State.ROLE_NOT_CHOOSED_ERR,e);
        }else{
            return Result.failure(Result.State.UNKNOWN_ERR,e);
        }
    }

    @ExceptionHandler(ShiroException.class)
    public Result handleShiroException(ShiroException e){
        if(e instanceof UnknownAccountException){
            return Result.failure(Result.State.UNKNOWN_ACCOUNT_ERR,e);
        }else if(e instanceof LockedAccountException){
            return Result.failure(Result.State.LOCKED_ACCOUNT_ERR,e);
        }else if(e instanceof IncorrectCredentialsException){
            return Result.failure(Result.State.INCORRECT_CRRDENTIALS_ERR,"密码错误!");
        }else if(e instanceof AuthorizationException){
            return Result.failure(Result.State.AUTH_ORIZATION_ERR,"当前用户没有此操作权限!");
        }else{
            return Result.failure(Result.State.UNKNOWN_ERR,e);
        }
    }
}
